// pages/order-confirm/order-confirm.js
const util = require('../../utils/util.js')
const api = require('../../utils/api.js')
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartArr: [
      { "name": "微信", "icon": "icon-weixinzhifu", value: 'weixin' },
      // { "name": "余额支付", "icon": "icon-yuezhifu", value: 'yue' },
      // { "name": "线下付款", "icon": "icon-wallet", value: 'offline' },
      // { "name": "到店自提", "icon": "icon-dianpu", value: 'ziti'  },
    ],
    
    mark: '',
    payType: 'weixin',

    addressArray:null,
    defaultAddress:null,
    addressId:'',
    cartItems:null,
    fromcart: true,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var pages = getCurrentPages();
    var Page = pages[pages.length - 1];//当前页
    var prevPage = pages[pages.length - 2];  //上一个页面
    if (options.fromcart)
    {
      var cartItems = prevPage.data.checkItems //取上页data里的数据
      var totalPrice = prevPage.data.totalPrice
      that.setData({
        cartItems: cartItems,
        totalPrice: totalPrice,
        fromcart:true,
      })
    }
    else{
      let item =[{
        amount: options.amount,
      }]
      that.setData({
        fromcart: false,
        skuid: options.skuid,
        cartItems: item,
        totalPrice: options.amount * prevPage.data.selectedSku.price,
      })
      that.getSKu()
    }
  },
  getSKu:function()
  {
    let that = this
    let url = api.GetSkuByIdUrl
    util.request(url, {
      skuid: that.data.skuid,
    }).then(function (res) {
      if (res.status == 'success') {
        if (!res.data) {
          util.showErrorToast("sku已删除");
        }
        else {
          that.data.cartItems[0].product_sku = res.data.sku
          that.setData({
            cartItems: that.data.cartItems,
          });
        }
      } else {
        if (typeof (res.data) == 'string') {
          util.showErrorToast(res.data);
        } else {
          util.showErrorToast("错误，请重试");
        }
      }
    })
  },
  getAddress: function () {
    wx.showToast({
      title: '加载地址...',
      icon:'none'
    })
    var that = this;
    util.requestByToken(api.GetAddressUrl).then(function (res) {
      wx.hideToast();
      if (res.status == 'success') {
        that.setData({
          addressArray: res.data.addresses,
        })
        for (var i in res.data.addresses) {
          if (res.data.addresses[i].is_default == 1) {
            that.setData({
              defaultAddress: res.data.addresses[i]
            })
          }
        }
        if (!that.data.defaultAddress) {
          that.setData({
            defaultAddress: res.data.addresses[0]
          })
        }
      } else {
        util.showErrorToast(res.data);
      }
    })
  },
  bindHideKeyboard: function (e) {
    this.setData({
      mark: e.detail.value
    })
  },
  radioChange: function (e) {
    this.setData({
      payType: e.currentTarget.dataset.value
    })
  },
  subOrder: function (e) {
    var that = this;
    if (that.data.payType == '') {
      wx.showToast({
        title: '请选择支付方式',
        icon: 'none',
        duration: 1000,
      })
    } else if (!that.data.defaultAddress) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none',
        duration: 1000,
      })
    } else {
      wx.showToast({
        title: '创建订单...',
        icon:'none'
      })
      let that = this
      util.requestByToken(api.CreateOrderUrl,
        {
          fromcart: that.data.fromcart,
          address_id: that.data.defaultAddress.id,
          remark: that.data.mark,
          items: that.data.cartItems,

        }, 'POST').then(function (res) {
          if (res.status == 'success') {
            var jsConfig = res.data.conf;
            wx.requestPayment({
              timeStamp: jsConfig.timestamp,
              nonceStr: jsConfig.nonceStr,
              package: jsConfig.package,
              signType: jsConfig.signType,
              paySign: jsConfig.paySign,
              success: function (r) {
                wx.showToast({
                  title: '支付成功',
                  icon: 'success',
                  duration: 1000,
                })
                setTimeout(function () {
                  wx.redirectTo({
                    url: '/pages/orderDetail/orderDetail?order_id=' +res.data.order_id
                  })
                }, 1200)
              },
              fail: function (r) {
                wx.showToast({
                  title: '支付取消',
                  icon: 'none',
                  duration: 1000,
                })
                setTimeout(function () {
                  wx.redirectTo({
                    url: '/pages/orderDetail/orderDetail?order_id=' + res.data.order_id
                  })
                }, 1200)
              },
              complete: function (r) {
                if (r.errMsg == 'requestPayment:cancel') {
                  wx.showToast({
                    title: '取消支付',
                    icon: 'none',
                    duration: 1000,
                  })
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '/pages/orderDetail/orderDetail?order_id=' + res.data.order_id
                    })
                  }, 1200)
                }
              },
            })
          } else {
            util.showErrorToast(res.data);
          }
        })
    }
  },
  toAddress: function () {
    var that = this;
    wx.navigateTo({ //跳转至指定页面并关闭其他打开的所有页面（这个最好用在返回至首页的的时候）
      url: '/pages/address/address?backorder=1'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    if (that.data.addressId) {
      util.requestByToken(api.GetAddressByIdUrl, { 'id': that.data.addressId }).then(function (res) {
        if (res.status == 'success') {
          that.setData({
            addressArray: res.data.address,
            defaultAddress: res.data.address
          })
        } else {
          util.showErrorToast(res.data);
        }
      })
    }
    else {
      that.getAddress()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})